let util = require("@/utils/util");
let disp = require("@/utils/broadcast");

var onMessage = function(that, message) {
  var msg = JSON.parse(message.data);
  switch (msg.message_type) {
    case 'init':
      bind(that, msg);
      return;
    case 'chatMessage':
      saveMsg(that, msg.data, 'accept');
      return;
    case 'event':
      if(msg.data){
        disp.fire(msg.do,JSON.parse(msg.data));
      }
      else{
        disp.fire(msg.do);
      }
      return;
  }
};
var bind = function(that, msg) {
  that.$http.post('/app.im.bind', {client_id: msg.client_id,platform: 'web'}).then((res) => {
    if (res.data.code == 0) {
      var msgs = res.data.data.unread_message;
      for (var key in msgs) {
        console.log(JSON.parse(msgs[key]));
        saveMsg(that, JSON.parse(msgs[key]), 'accept');
      }
    }
  });
};
var msgAcceptCallBack = function(that){
  that.$http.post('/app.im.msgAcceptCallBack');
};
var saveMsg = function(that, message, type) {
  if (type == "send") {
    message.read = 1;
  } else {
    if (that.chatWindowsId != message.id || that.mainTab!='chat' || that.winFocus==0) {
      message.read = 0;
    } else {
      message.read = 1;
    }
  }

  var historyMsgListCopy = {};
  var local = {};
  if (that.historyMsgList != null && that.historyMsgList != '') {
    if (that.historyMsgList[that.userInfo.user_id] != null && that.historyMsgList[that.userInfo.user_id] != '') {
      if (type == "send") {
        local = that.historyMsgList[that.userInfo.user_id][message.type + message.to['id']] || {};
      } else {
        local = that.historyMsgList[that.userInfo.user_id][message.type + message.id] || {};
      }
    }
  }

  var chatlog = local.chatlog || [];
  if (chatlog) {
    chatlog.push(message);
    if (chatlog.length > 50) {
      chatlog.shift();
    }
  } else {
    chatlog = [message];
  }


  var history = local.history || {};
  history = [message];



  local.chatlog = chatlog;
  local.history = history;
  historyMsgListCopy = util.deepCopy(that.historyMsgList || {});
  var myHistoryMsg = historyMsgListCopy[that.userInfo.user_id] || {};

  if (type == "send") {
    myHistoryMsg[message.type + message.to['id']] = local;
  } else {
    myHistoryMsg[message.type + message.id] = local;
  }
  historyMsgListCopy[that.userInfo.user_id] = myHistoryMsg;

  that['chatModule/setHistoryMsgList'](historyMsgListCopy);

  that.setStore('historyMsgList', historyMsgListCopy);

  getUnreadMsgTotal(that);

  if (type == "accept") {
    //新消息提醒
    if(that.isElectron){
      that.ipcRenderer.send('MAINWIN:notify',JSON.stringify(message));
    }
    msgAcceptCallBack(that);
  }

};
var getUnreadMsgTotal = function(that) {
  var num = 0;
  var getUnReadCount = function(chatlog) {
    var i = 0;
    for (var n = 0; n < chatlog.length; n++) {
      if (chatlog[n].read == 0) {
        i++;
      }
    }
    return i;
  };
  if (that.historyMsgList != null && that.historyMsgList != '') {
    if (that.historyMsgList[that.userInfo.user_id] != null && that.historyMsgList[that.userInfo.user_id] != '') {
      var local = that.historyMsgList[that.userInfo.user_id] || {};
      for (var key in local) {
        num = num + getUnReadCount(local[key]['chatlog']);
      }
    }
  }
  that['chatModule/setUnreadMsgCount'](num);
  //更新角标
  if(that.isElectron){
    that.ipcRenderer.send('MAINWIN:badge',num);
  }
};
var initLocalData = function(that) {
  var historyMsgList = that.getStore('historyMsgList');
  if( typeof(historyMsgList)=="string" ){
    historyMsgList = JSON.parse(historyMsgList);
  }
  that['chatModule/setHistoryMsgList'](historyMsgList);
  getUnreadMsgTotal(that);
};
var sendMsg = function(that, msg, s_cb, f_cb) {
  that.$http.post('/app.im.sendMsg', {json_data:JSON.stringify(msg)}).then((res) => {
      if (res.data.code == 0) {
        s_cb(res);
      } else {
        f_cb(res);
      }
    }).catch((res) =>{
      f_cb(res);
    });
};
var sendStatus = function(that, msg, status) {
  var historyMsgListCopy = util.deepCopy(that.historyMsgList);
  var myChatLog = historyMsgListCopy[that.userInfo.user_id][that.msgType + msg.to['id']]['chatlog'] || [];
  for (var i = 0; i < myChatLog.length; i++) {
    if (myChatLog[i]['mine'] && myChatLog[i]['timestamp'] == msg.timestamp) {
      if (status) {
        myChatLog[i]['send'] = 2; //发送成功
      } else {
        myChatLog[i]['send'] = 1; //发送失败
      }
    }
  }
  that['chatModule/setHistoryMsgList'](historyMsgListCopy);
  that.setStore('historyMsgList', historyMsgListCopy);
};
var changePicUrl = function(that, msg, url) {
  var historyMsgListCopy = util.deepCopy(that.historyMsgList);
  var myChatLog = historyMsgListCopy[that.userInfo.user_id][that.msgType + msg.to['id']]['chatlog'] || [];
  for (var i = 0; i < myChatLog.length; i++) {
    if (myChatLog[i]['mine'] && myChatLog[i]['timestamp'] == msg.timestamp) {
      myChatLog[i]['content'] = "img["+url+"]";
    }
  }
  that['chatModule/setHistoryMsgList'](historyMsgListCopy);
  that.setStore('historyMsgList', historyMsgListCopy);
};
module.exports = {
  onMessage: onMessage,
  msgAcceptCallBack: msgAcceptCallBack,
  saveMsg: saveMsg,
  getUnreadMsgTotal: getUnreadMsgTotal,
  initLocalData: initLocalData,
  sendMsg: sendMsg,
  sendStatus: sendStatus,
  changePicUrl: changePicUrl
}
